import React, {
    Component,
} from 'react';

import {
    StyleSheet,
    Text,
    View,
    Platform,
    FlatList,
    Dimensions,
    TouchableOpacity,
    Image,
    ScrollView,
    StatusBar,
    Linking,
    ActivityIndicator,
    DeviceEventEmitter,
    TextInput,
    Alert
} from 'react-native';

import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import Constant from '../../utils/Constant'//全局变量
import Header from "../../components/header";
import { ToastToUser } from '../../utils/CustomToast';
import Loading from "../../utils/Loading";

import NoData from '../../utils/NoData'
import { payType } from '../../utils/Enum';

let navigation = null;

const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;

/**
 * 签署合同选择授权主体
 */
export default class SignMainBodyPage extends Component {

    constructor(props) {
        super(props);
        this.state = {
            authorizeList: [],
            isRefresh: false,
            showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            pageNo: 1,
            orderNo: this.props.route.params.orderNo,
            from: this.props.route.params.from,//order订单  afterSales售后订单
            afterSalesType: this.props.route.params.afterSalesType,
            payType: this.props.route.params.payType, // 1 是全款预付订单 0 其他
        }
    }

    componentWillUnmount() {

    }

    componentDidMount() {
        this.refreshData()
    }


    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'选择主体'} />

                {this.renderList()}

            </View>
        )
    }


    renderList() {
        return (
            <View style={{ flex: 1 }}>
                <FlatList
                    showsVerticalScrollIndicator={false}
                    data={this.state.authorizeList}
                    renderItem={this.renderItemView.bind(this)}
                    ListHeaderComponent={<View style={{ height: 10 }}></View>}
                    extraData={this.state}
                    ListFooterComponent={this.renderFooter.bind(this)}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={0.2}
                    onRefresh={this.refreshData}
                    refreshing={this.state.isRefresh}
                    ListEmptyComponent={this.renderEmpty.bind(this)}
                />

                <Loading onRef={(ref) => (this.Loading = ref)} />
            </View>
        )
    }

    renderItemView({ item, index }) {

        return (
            <TouchableOpacity key={index} activeOpacity={1}
                onPress={() => {

                }}>

                <View style={[styles.authorizeItemContainer, { borderTopLeftRadius: index == 0 ? 6 : 0, borderTopRightRadius: index == 0 ? 6 : 0, borderBottomLeftRadius: index == this.state.authorizeList.length - 1 ? 6 : 0, borderBottomRightRadius: index == this.state.authorizeList.length - 1 ? 6 : 0 }]} key={index}>

                    <View style={{ flex: 1, marginRight: 10, marginBottom: 15 }}>
                        {/* 公司名称 */}
                        <View style={{ flexDirection: 'row', width: '100%', marginTop: 16}}>
                            <Text style={styles.companyName}>{item.orgName}</Text>
                        </View>

                        {/* 经办人 */}
                        <Text style={styles.handlerbyperson}>经办人：{item.psnMobile}</Text>
                        {/* 授权状态 */}
                        <View style={item.authorizedStatus == 1 ? styles.statusContainer1 : styles.statusContainer}>
                            <Text style={item.authorizedStatus == 1 ? styles.status1 : styles.status}>{this.getstatus(item)}</Text>
                        </View>

                    </View>

                    {/* 选择主体 */}

                    {
                        item.authorizedStatus == 1
                            ?
                            <View>
                                <TouchableOpacity style={styles.cancelContainer}  onPress={() => {
                                    this.submitContract(item)
                                }}>
                                    <Text style={styles.cancelTitle}>{'选择'}</Text>
                                </TouchableOpacity>
                            </View>
                            :
                            null
                    }



                    {
                        index != this.state.authorizeList.length - 1
                            ?
                            <View style={styles.borderBottom} >
                            </View>
                            :
                            null
                    }


                </View>

            </TouchableOpacity>
        )
    }

    getstatus(item) {
        if (item.authorizedStatus == 0) {
            return '过期失效'
        } else if (item.authorizedStatus == 1) {
            return '已授权'
        } else if (item.authorizedStatus == 2) {
            return '等待授权'
        } else if (item.authorizedStatus == 3) {
            return '审批未通过'
        } else if (item.authorizedStatus == 4) {
            return '已取消授权'
        } else {
            return '未确认'
        }
    }

    refreshData = () => {
        this.setState({
            isRefresh: true,
            pageNo: 1,
            authorizeList: []
        }, function () {
            this.getAuthorizeLists()
        })
    }

    getAuthorizeLists() {

        let param = {
            pageNo: this.state.pageNo,
            pageSize: 20,
            merchantId: Constant.userInfo.merchantId,
            authorizedStatus: [1]
        }

        HttpUtils.postRequest(HttpUrls.merchantAuthList, param)
            .then((result) => {

                let data = result.data
                if (data) {
                    let resultList = data.resultList

                    if (resultList && resultList != null && resultList.length > 0) {

                        this.setState({
                            authorizeList: this.state.authorizeList.concat(resultList),
                            isRefresh: false,
                            showFoot: 1,
                        });
                        setTimeout(() => {
                            this.setState({
                                showFoot: resultList.length >= 20 ? 0 : 1,
                            })

                        }, 200);
                    } else {
                        this.setState({
                            showFoot: 1,
                            isRefresh: false,
                        });
                    }
                } else {
                    this.setState({
                        showFoot: 1,
                        isRefresh: false,
                    });
                }
            })
            .catch((error) => {

            });
    }


    renderEmpty() {
        if (!this.state.isRefresh) {
            return (
                <NoData Desc="暂无数据" style={{ marginTop: gREM(200) }} />
            )
        } else {
            return (
                null
            )
        }
    }

    renderFooter() {
        if (this.state.showFoot === 1) {
            return <View style={{ height: Constant.bottomHeight }} />;
        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator size="small" color="#999999" />
                    <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return null;
        }
    }



    _onEndReached() {
        //如果是正在加载中或没有更多数据了，则返回
        if (this.state.showFoot != 0) {
            return null;
        }

        //底部显示正在加载更多数据
        this.setState(
            {
                showFoot: 2,
                pageNo: this.state.pageNo + 1
            }, function () {
                this.getAuthorizeLists()
            });


    }

    submitContract(item){
        if(this.Loading){
            this.Loading.show('合同发起中...');
        }

        let param = {
            orderNo: this.state.orderNo,
            operator: Constant.userInfo.fullname,
            
        }

        if(this.state.from == 'afterSales'){
            if(this.state.afterSalesType == 1){
                param.bizType = 4
            }else if(this.state.afterSalesType == 2){
                param.bizType = 5
            }
            param.initiatorEsignAuthId = item.id
        }else{
            param.bizType = 3
            param.buyerEsignAuthId = item.id

            if(this.state.payType == payType.payTypeFull){ // 全款预付订单
                param.bizType = 6
            }

        }

        HttpUtils.postRequest(HttpUrls.createSystemTransactionContract, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide()
                }
                if (result.code == 0) {
                    setTimeout(() => {
                        DeviceEventEmitter.emit('refreshOrderDetail', {})
                    },500)
                    
                    setTimeout(() => {
                        navigation.replace('ContractDetailPage', { contractNo: result.data.contractNo, orderNo: this.state.orderNo });
                    }, 1000);
                    
                }else{
                    ToastToUser(result.msg+'')
                }
            })
            .catch((error) => {

            })
    }

}

const styles = StyleSheet.create({

    container: {
        width: screenW,
        flex: 1,
        backgroundColor: '#f6f6f6'
    },

    authorizeManagerContainer: {
        marginTop: 16,
        marginLeft: 16,
        marginRight: 16,
        height: 48,
        width: screenW - 32,
        backgroundColor: '#ffffff',
        alignItems: 'center',
        flexDirection: 'row',
        borderRadius: 6,
    },

    authorizeTitle: {
        marginLeft: 12,
        fontWeight: '400',
        fontSize: 16,
        color: '#333333'
    },

    addauthorizeTitle: {
        fontWeight: '400',
        fontSize: 16,
        color: '#333333',
        position: 'absolute',
        right: 42,
        fontWeight: '400',
        fontSize: 14,
        color: '#666666',

    },

    authoniceadd: {
        width: 24,
        height: 24,
        position: 'absolute',
        right: 12,
    },

    authorizeItemContainer: {
        // height: 100,
        marginLeft: 16,
        marginRight: 16,
        width: screenW - 32,
        backgroundColor: '#ffffff',
        // position: 'relative',
        flexDirection: 'row',
        alignItems: 'center',
    },

    companyName: {
        fontWeight: '400',
        fontSize: 16,
        color: '#333333',
        flex: 1,
        marginLeft: 12
    },

    handlerbyperson: {
        fontWeight: '400',
        fontSize: 14,
        color: '#999999',
        marginTop: 6,
        marginLeft: 12
    },

    statusContainer: {
        backgroundColor: 'rgba(249,152,2,0.1)',
        width: 42,
        height: 16,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 1,
        marginTop: 6,
        marginLeft: 12
    },

    statusContainer1: {
        backgroundColor: 'rgba(110,204,73,0.1)',
        width: 42,
        height: 16,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 1,
        marginTop: 6,
        marginLeft: 12
    },

    status: {
        fontWeight: '500',
        fontSize: 8,
        color: '#F99802',
    },

    status1: {
        fontWeight: '500',
        fontSize: 8,
        color: '#2CE454',
    },


    cancelContainer: {
        right: 12,
        width: 72,
        height: 28,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 3,
        borderColor: '#E5E5E5',
        borderWidth: 0.8,
    },

    cancelTitle: {
        fontWeight: '400',
        fontSize: 12,
        color: '#333333',
    },

    borderBottom: {
        borderBottomColor: '#E4E4E4',
        borderBottomWidth: 1,
        marginLeft: 12,
        marginRight: 12,
        position: 'absolute',
        bottom: 0,
        width: screenW - 32 - 24,
    },



    addauthorizeLayout: {
        marginLeft: 15,
        marginRight: 15,
        width: screenW - 30,
        height: 46,
        backgroundColor: '#FFE000',
        borderRadius: 4,
        alignItems: 'center',
        justifyContent: 'center',
    },

    addTitle: {
        fontWeight: '500',
        fontSize: 15,
        color: '#222222',
    },

    footer: {
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f6f6f6'
    },
    loadMoreTextStyle: {
        fontSize: 14,
        color: '#999999',
        marginStart: 10,
    },


})